<?php

use com\gdl\kq\dataobject\approvalprocess\approvalProcessDTO;
use com\gdl\common\dataobject\common\ResultDO;
use com\gdl\kq\interfaces\ApprovalProcessServiceIf;
/**
 *  审批流程
 *  @author gdl
 */
class api_ApprovalProcessService extends api_Abstract implements ApprovalProcessServiceIf
{
    /**
     * 获得审批流程列表
     * @param  type @1请假流程 2外出流程 3补卡流程
     * @param  status @1默认流程 2特定流程 3特殊人群流程
     * @param  platformid @平台ID
     * @param approvalProcessDTO $approvalprocess
     * @return ResultDO
     */
    public function getApprovalProcessList(approvalProcessDTO $approvalprocess){
        $status = $approvalprocess->status ? gdl_lib_BaseUtils::getStr($approvalprocess->status) : 0;
        $type = $approvalprocess->type ? gdl_lib_BaseUtils::getStr($approvalprocess->type) : 0;
        $platformId = $approvalprocess->platformId ? gdl_lib_BaseUtils::getStr($approvalprocess->platformId) : 0;
        $id = $approvalprocess->id ? gdl_lib_BaseUtils::getStr($approvalprocess->id) : 0;
        $name = $approvalprocess->name ? gdl_lib_BaseUtils::getStr($approvalprocess->name) : '';
        $data = $approvalprocess->data ? gdl_lib_BaseUtils::getStr($approvalprocess->data) : [];

        $result = new ResultDO();
        $result->success = true;
        $result->code = 400;
        $result->data = [];

        #验证
        if(empty($platformId)){$result->message = "缺少必要条件"; return $result;}

        #分页
//        if($offset=='0') $offset=1;
//        $limit = ($offset - 1) * $num . "," . $num;
//        $group = 'order by id desc limit '.$limit;
        $count = 0;
        try{
            $approvalprocessModel = new model_attendance_approvalprocess();
            $adminUserId = $data['adminUserId'];
            if ($status==3){//特殊人员审批列表
                $adminUserId = $data['adminUserId'];
                $unitids = $data['unitids'];
                $agId = $data['agId'];
                //获取当前平台的组织架构和考勤用户的关联数组
                $serviceUserModel       = new service_user();
                $UnitsList = $serviceUserModel->getMemberUnitsRelation($platformId,$adminUserId,2);
                $specialpeopleModel = new model_attendance_approvalprocessspecialpeople();

                $approvalprocessWhere = " atd_approval_process_special_people.platformId = $platformId ";
                if ($name){
                    $approvalprocessWhere.=" and ag.title like '%{$name}%'";
                }
                if ($unitids){
                    $approvalprocessWhere.= " and am.unitId in({$unitids})";
                }

                if ($agId){
                    $approvalprocessWhere.= " and ag.id = {$agId}";
                }
                $join = array(
                    'atd_approval_process as aap'=>'aap.id=atd_approval_process_special_people.approvalProcessId',
                    'atd_member as am'=>'am.id=atd_approval_process_special_people.memberId',
                    'atd_attendance_group_user as agu'=>'agu.memberId=atd_approval_process_special_people.memberId',
                    'atd_attendance_group as ag'=>'ag.id=agu.agId',
                );

                if ($id){
                    $approvalprocessWhere.= " and aap.id = {$id}";
                    $dataR = [];
                    $userList = $specialpeopleModel->select(
                        $approvalprocessWhere,
                        'am.id memberId,am.realName,am.departmentId,ag.title agName,aap.rules,aap.name,aap.id','group by am.id','',$join)->items;

                    if ($userList){
                        foreach ($userList as $value){
                            $dataR['memberId'][] = ['realName'=>$value['realName'],'uid'=>$value['memberId']];
                            $dataR['id'] = $value['id'];
                            $dataR['name'] = $value['name'];
                            $dataR['agName'] = $value['agName'];
                            $dataR['rules'] = $value['rules'];
                        }
                        $dataR['memberId'] =serialize($dataR['memberId']);

                        $userList =[$dataR];
                    }else{
                        $userList = [[]];
                    }
                }else{
                    $userList = $specialpeopleModel->select(
                        $approvalprocessWhere,
                        'am.id memberId,am.realName,am.departmentId,ag.title agName,aap.rules,aap.name,aap.id','group by atd_approval_process_special_people.memberId','',$join)->items;

                    if ($userList){
                        foreach ($userList as &$value){
                            if (isset($UnitsList['relation'][$value['departmentId']])){
                                $organizationName = $UnitsList['relation'][$value['departmentId']]['title'];
                            }else{
                                $organizationName = "本组织";
                            }
                            $value['organizationName'] = $organizationName;
                        }
                    }else{
                        $userList = [[]];
                    }

                }

                $count = $specialpeopleModel->selectOne($approvalprocessWhere, "count(*) num");
                $count = !empty($count['num'])?$count['num']:0;
            }else{//审批列表
                $approvalprocessFiled = "*";

                $approvalprocessWhere = " status = {$status}  and adminUserId={$adminUserId} and stop=1 and platformId={$platformId} ";
                if ($type){
                    $approvalprocessWhere.=" and type = {$type} ";
                }
                if ($id)$approvalprocessWhere.= " and id = {$id}";
                $userList = $approvalprocessModel->select($approvalprocessWhere, $approvalprocessFiled)->items;
                $count = $approvalprocessModel->selectOne($approvalprocessWhere, "count(*) num");
                $count = !empty($count['num'])?$count['num']:0;
            }
            //var_dump($userModel);exit;
            if($userList){
                $result->message = "获取成功";
                $result->code = 200;
                $result->counts = $count;
                $result->data = $userList;
            }else{
                $result->counts = $count;
                $result->message = "暂无数据";
            }

        }catch(Exception $ex){
            $result->counts = $count;
            $result->message = $ex->getMessage();
        }

        return $result;
    }

    //添加审批流程
    public function addApprovalProcess(approvalProcessDTO $approvalprocess){
        $data = $approvalprocess->data ? $approvalprocess->data : "";

        #实例化返回
        $result = new ResultDO();
        $result->success = true;
        $result->code = 0;
        $result->data = [];

        #验证
        if(empty($data)){
            $result->message = "缺少必要参数";
            return $result;
        }

        #处理data

        #业务
        try{
            $memberIds = $data['memberIds'];
            $status = $data['status'];
            $platformId = $data['platformId'];
            unset($data['memberIds']);
            $approvalprocessModel = new model_attendance_approvalprocess();
            #验证
            #插入数据
            $ret = $approvalprocessModel->insert($data);
            if ($memberIds && $status==3){//逗号分割的人员ID
                $memberIds = explode(',',$memberIds);
                $specialpeopleModel =  new model_attendance_approvalprocessspecialpeople();
                foreach ($memberIds as $memberId){
                    $me = $specialpeopleModel->selectOne(" memberId = '{$memberId}'");
                    if ($me){
                        $specialpeopleModel->update(" memberId='{$memberId}'",['approvalProcessId'=>$ret]);
                    }else{
                        $specialpeopleModel->insert(['approvalProcessId'=>$ret,'memberId'=>$memberId,'platformId'=>$platformId]);
                    }
                }
            }

            if($ret){
                $result->code = 1;
                $result->message = "添加成功";
            }else{
                $result->code = 0;
                $result->message = "添加异常";
            }
        } catch (Exception $e) {
            $result->success = true;
            $result->code = 0;
            $result->message = $e->getMessage();
        }

        return $result;
    }
    //操作审批流程
    public function operationApprovalProcess(approvalProcessDTO $approvalprocess){
        $data = $approvalprocess->data ? $approvalprocess->data : "";

        #实例化返回
        $result = new ResultDO();
        $result->success = true;
        $result->code = 0;
        $result->data = [];

        #验证
        if(empty($data)){
            $result->message = "缺少必要参数";
            return $result;
        }

        #处理data

        #业务
        try{
            $id = $data['id'];
            $do = $data['do'];
            unset($data['do']);
            $memberIds = $data['memberIds'];
            $status = $data['status'];
            $platformId = $data['platformId'];
            unset($data['memberIds']);
            $approvalprocessModel = new model_attendance_approvalprocess();
            #验证
            if ($do==1){//1添加 2删除
                unset($data['id']);
                #插入数据
                $ret = $approvalprocessModel->insert($data);
                if ($memberIds && $status==3){//逗号分割的人员ID
                    $memberIds = explode(',',$memberIds);
                    $specialpeopleModel =  new model_attendance_approvalprocessspecialpeople();
                    foreach ($memberIds as $memberId){
                        $me = $specialpeopleModel->selectOne(" memberId = '{$memberId}'");
                        if ($me){
                            $specialpeopleModel->update(" memberId='{$memberId}'",['approvalProcessId'=>$ret]);
                        }else{
                            $specialpeopleModel->insert(['approvalProcessId'=>$ret,'memberId'=>$memberId,'platformId'=>$platformId]);
                        }
                    }
                }
            }else{
                #编辑数据
                $ret = $approvalprocessModel->update(['id'=>$id],$data);
                if ($memberIds && $status==3){//逗号分割的人员ID
                    $memberIds = explode(',',$memberIds);
                    $specialpeopleModel =  new model_attendance_approvalprocessspecialpeople();
                    foreach ($memberIds as $memberId){
                        $me = $specialpeopleModel->selectOne(" memberId = '{$memberId}'");
                        if ($me){
                            $specialpeopleModel->update(" memberId='{$memberId}'",['approvalProcessId'=>$id]);
                        }else{
                            $specialpeopleModel->insert(['approvalProcessId'=>$id,'memberId'=>$memberId,'platformId'=>$platformId]);
                        }
                    }
                }
            }


            if($ret){
                $result->code = 1;
                $result->message = "添加成功";
            }else{
                $result->code = 0;
                $result->message = "添加异常";
            }
        } catch (Exception $e) {
            $result->success = true;
            $result->code = 0;
            $result->message = $e->getMessage();
        }

        return $result;
    }

    //编辑审批流程
    public function editApprovalProcess(approvalProcessDTO $approvalprocess){
        $data = $approvalprocess->data ? gdl_lib_BaseUtils::getStr($approvalprocess->data) : "";
        $id = $approvalprocess->id ? gdl_lib_BaseUtils::getStr($approvalprocess->id) : 0;

        #实例化返回
        $result = new ResultDO();
        $result->success = true;
        $result->code = 0;
        $result->data = [];

        #验证
        if(empty($data) || empty($id)){
            $result->message = "缺少必要参数";
            return $result;
        }

        #处理data

        #业务
        try{
            $memberIds = $data['memberIds'];
            $status = $data['status'];
            $platformId = $data['platformId'];
            unset($data['memberIds']);
            $approvalprocessModel = new model_attendance_approvalprocess();
            #验证

            #插入数据
            $ret = $approvalprocessModel->update(['id'=>$id],$data);
            if ($memberIds && $status==3){//逗号分割的人员ID
                $memberIds = explode(',',$memberIds);
                $specialpeopleModel =  new model_attendance_approvalprocessspecialpeople();
                foreach ($memberIds as $memberId){
                    $me = $specialpeopleModel->selectOne(" memberId = '{$memberId}'");
                    if ($me){
                        $specialpeopleModel->update(" memberId='{$memberId}'",['approvalProcessId'=>$ret]);
                    }else{
                        $specialpeopleModel->insert(['approvalProcessId'=>$ret,'memberId'=>$memberId,'platformId'=>$platformId]);
                    }
                }
            }
            if($ret){
                $result->code = 1;
                $result->message = "添加成功";
            }else{
                $result->code = 0;
                $result->message = "添加异常";
            }
        } catch (Exception $e) {
            $result->success = true;
            $result->code = 0;
            $result->message = $e->getMessage();
        }

        return $result;
    }

    //删除审批流程
    public function deleteApprovalProcess(approvalProcessDTO $approvalprocess){
        $id = $approvalprocess->id ? gdl_lib_BaseUtils::getStr($approvalprocess->id) : 0;
        $data = $approvalprocess->data ? $approvalprocess->data : [];
        $result = new ResultDO();
        $result->success = true;
        $result->message = "您已删除，请勿重复操作";
        $result->code = 400;
        $result->data = [];
//        if(empty($platformId)){
//            $result->message = "您还没有选择平台";
//            return $result;
//        }
        if(empty($id)){
            $result->message = "参数错误";
            return $result;
        }
        $userId = $data['userId'];
        try{
            $approvalprocessModel = new model_attendance_approvalprocess();
            $specialpeopleModel = new model_attendance_approvalprocessspecialpeople();
            $attendancegroupModel = new model_attendance_attendancegroup();

                $apInfo = $approvalprocessModel->selectOne(" id = {$id} ");
                if ($apInfo){
                    //考勤组查询是否有该流程选择
                    $con = " isDelete=0";
                    if ($apInfo['type']==1){
                        $con.=" and approvalProcessOne={$id} ";
                    }elseif($apInfo['type']==2){
                        $con.=" and approvalProcessTwo={$id} ";
                    }elseif($apInfo['type']==3){
                        $con.=" and approvalProcessThree={$id} ";
                    }
					if($apInfo['status']!=3){
						$ty = $attendancegroupModel->selectOne($con);
					}else{
						$ty = false;
					}

	
                    if ($ty) {
                        $result->code = 400;
                        $result->message = "删除失败,考勤组{$ty['title']}已经设置该流程,调整后删除";
                    }else {
                        if ($userId && $apInfo['status']==3){//特殊人员
                            $num = $specialpeopleModel->selectOne(" approvalProcessId = {$id} ",'count(id) num');
                            $res = $specialpeopleModel->delete(" memberId = {$userId} ");
                            if ($num['num']==1){
                                $where = " id = {$id} ";
                                $res = $approvalprocessModel->delete($where);
                            }
                        }else{
                            $where = " id = {$id} ";
                            $res = $approvalprocessModel->delete($where);
                        }
                        if($res){
                            $result->code = 200;
                            $result->message = "已删除";
                        }
                    }

                }else{
                    $result->code = 200;
                    $result->message = "已删除";
                }


        } catch (Exception $e) {
            $result->success = false;
            $result->code = $e->getCode();
            $result->message = $e->getMessage();
        }
        return $result;
    }

    //审批流程 启用及其停用
    public function stopApprovalProcess(approvalProcessDTO $approvalprocess){
        $id = $approvalprocess->id ? gdl_lib_BaseUtils::getStr($approvalprocess->id) : 0;
        $stop = $approvalprocess->stop ? gdl_lib_BaseUtils::getStr($approvalprocess->stop) : 0;//1启用 2停用
        $type = $approvalprocess->type ? gdl_lib_BaseUtils::getStr($approvalprocess->type) : 0;//1请假流程 2外出流程 3补卡流程
        $status = $approvalprocess->status ? gdl_lib_BaseUtils::getStr($approvalprocess->status) : 0;//1默认流程 2特定流程 3特殊人群流程
        $platformId = $approvalprocess->platformId ? gdl_lib_BaseUtils::getStr($approvalprocess->platformId) : 0;
        $result = new ResultDO();
        $result->success = true;
        $result->message = "参数错误，请勿操作";
        $result->code = 400;
        $result->data = [];
        if(empty($platformId)){
            $result->message = "参数错误";
            return $result;
        }
        try{
            if ($status==1){
                $approvalprocessModel = new model_attendance_approvalprocess();
                $rStop = $approvalprocessModel->selectOne(
                    " type = {$type} and status = {$status} and platformId = {$platformId}",'stop');
                if ($rStop==1 && $rStop==$stop){
                    $result->message = "已经启用,请勿重复开启";
                    return $result;
                }elseif ($rStop==2 && $rStop==$stop){
                    $result->message = "已经停用,请勿重复开启";
                    return $result;
                }else{
                    $where = " type = {$type} and status = {$status} and platformId = {$platformId} ";
                    $data= ['stop'=>$stop];
                    $res = $approvalprocessModel->update($where,$data);
                }
            }else{
                $approvalprocessModel = new model_attendance_approvalprocess();
                $rStop = $approvalprocessModel->selectOne(" id = {$id}",'stop');
                if ($rStop==1 && $rStop==$stop){
                    $result->message = "已经启用,请勿重复开启";
                    return $result;
                }elseif ($rStop==2 && $rStop==$stop){
                    $result->message = "已经停用,请勿重复开启";
                    return $result;
                }else{
                    $where = " id = {$id} ";
                    $data= ['stop'=>$stop];
                    $res = $approvalprocessModel->update($where,$data);
                }
            }

            $result->code = 200;
            if ($stop==1){
                $result->message = "启用成功!";
            }else{
                $result->message = "停用成功!";
            }
        } catch (Exception $e) {
            $result->success = false;
            $result->code = 400;
            $result->message = $e->getMessage();
        }
        return $result;
    }
}
